/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 */
package com.apache.order.service.plugins;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.apache.api.manager.PluginConnector;
import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.order.entity.TOrder;
import com.apache.order.entity.TOrderDetail;
import com.apache.order.util.MessageUtil;

/**
 * description:  订单信息保存
 * @author Hou Dayu 创建时间：2015-8-10  
 */
public class OrderInfoSavePluginImpl implements PluginConnector {

	private ProxyManager<TOrder> orderProxyManager;

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see com.dwusoft.api.manager.PluginConnector#execute(com.dwusoft.api.vo.ParamsVo)  
	 */
	public Object execute(ParamsVo arg0) throws Exception {
		ResultEntity entity = new ResultEntity();
		entity.setResult("true");
		TOrder tOrderMain = setMethodParams(arg0);
		List<TOrderDetail> product = setProductInfo(arg0);
		ParamsVo vo = new ParamsVo();
		vo.setParams("order", tOrderMain);
		vo.setParams("product", product);
		vo.setKey("saveOrder");
		String id = String.valueOf(orderProxyManager.saveInvoke(vo));
		if (Validator.isNotNull(id)) {
			entity.setEntity(id);
			entity.setMessage(MessageUtil.getMessage("order-engine-0014", new String[0], "订单信息保存成功"));
			arg0.setParams("orderId", id);
			OrderEnginePluginUtil.newFixed().saveLogMessage(arg0);
		} else {
			entity.setMessage(MessageUtil.getMessage("order-engine-0015", new String[0], "订单信息保存失败"));
		}
		return entity;
	}

	private TOrder setMethodParams(ParamsVo vo) {
		TOrder tOrderMain = new TOrder();
		tOrderMain = (TOrder) MessageUtil.convert2Bean(vo.getParams(), tOrderMain);
		return tOrderMain;
	}

	@SuppressWarnings("unchecked")
	private List<TOrderDetail> setProductInfo(ParamsVo vo) {
		Object obj = vo.getParams("product");
		List<TOrderDetail> result = new ArrayList<TOrderDetail>();
		if (Validator.isEmpty(obj)) {
			TOrderDetail product = new TOrderDetail();
			product = (TOrderDetail) MessageUtil.convert2Bean(vo.getParams(), product);
			result.add(product);
		} else {
			List<Map> list = (List<Map>) obj;
			for (int i = 0; i < list.size(); i++) {
				TOrderDetail product = new TOrderDetail();
				product = (TOrderDetail) MessageUtil.convert2Bean(list.get(i), product);
				result.add(product);
			}
		}
		return result;
	}

	public void setOrderProxyManager(ProxyManager orderProxyManager) {
		this.orderProxyManager = orderProxyManager;
	}

}
